import { Router } from 'express';
import { UserController } from '@/controllers/user';
import { authenticateToken as auth } from '@/middleware/auth';
import validateRequest from '@/middleware/validateRequest';
import { body } from 'express-validator';
import { uploadMemorySingle } from '@/utils/upload';

const router = Router();
const userController = new UserController();

// 获取当前用户信息
router.get('/me', auth, userController.getCurrentUser);

// 更新用户资料
router.put('/me',
  auth,
  [
    body('nickname').optional().isLength({ min: 1, max: 50 }).withMessage('昵称长度必须在1-50字符之间'),
    body('avatar').optional().isURL().withMessage('头像必须是有效的URL'),
  ],
  validateRequest,
  userController.updateProfile
);

// 上传头像
router.post('/avatar',
  auth,
  uploadMemorySingle('avatar'),
  userController.uploadAvatar
);

/* 绑定/解绑（两人全量共享） */
router.post('/bind',
  auth,
  [ body('username').isString().isLength({ min: 1 }).withMessage('用户名必填') ],
  validateRequest,
  userController.bindPartner
);
router.delete('/bind', auth, userController.unbindPartner);

// 获取聊天对象信息
router.get('/other', auth, userController.getOtherUser);

// 更新在线状态
router.put('/online-status',
  auth,
  [
    body('isOnline').isBoolean().withMessage('在线状态必须是布尔值'),
  ],
  validateRequest,
  userController.updateOnlineStatus
);

// 修改密码
router.put('/change-password',
  auth,
  [
    body('currentPassword').isString().isLength({ min: 1 }).withMessage('当前密码必填'),
    body('newPassword').isString().isLength({ min: 6 }).withMessage('新密码至少6位'),
  ],
  validateRequest,
  userController.changePassword
);

// 管理员路由（隐藏的）
// 获取所有用户
router.get('/admin/all', auth, userController.getAllUsers);

// 更新用户信息
router.put('/admin/:userId',
  auth,
  [
    body('username').optional().isLength({ min: 1, max: 50 }).withMessage('用户名长度必须在1-50字符之间'),
    body('nickname').optional().isLength({ min: 1, max: 50 }).withMessage('昵称长度必须在1-50字符之间'),
    body('avatar').optional().isURL().withMessage('头像必须是有效的URL'),
  ],
  validateRequest,
  userController.updateUser
);

// 重置用户密码
router.put('/admin/:userId/reset-password',
  auth,
  [
    body('newPassword').isString().isLength({ min: 6 }).withMessage('新密码至少6位'),
  ],
  validateRequest,
  userController.resetUserPassword
);

// 删除用户
router.delete('/admin/:userId', auth, userController.deleteUser);

export { router as userRoutes };
export default router;